package com.manage.service;

import java.util.List;

import org.apache.log4j.Logger;

import com.manage.config.Config;
import com.manage.model.BlackNumber;
import com.service.AbstractService;
import com.util.ConfigUtil;
import com.utils.dbcp.ConnectionManager;
import com.utils.dbcp.ModelGenerator;

public class BlackNumberServiceImpl extends AbstractService implements BlackNumberService {
	
private Logger logger;
	
	public BlackNumberServiceImpl()
	{
		logger = Logger.getLogger(this.getClass());
		this.dbcp = ConfigUtil.get(Config.SECTION, Config.KEY_DBCP_NAME);
	}
	@Override
	public BlackNumber getBlackNumberById(int id) {
		String sql = "select * from blacknumber where id=" + String.valueOf(id) + "";
		ModelGenerator<BlackNumber> dbcpmg = new ModelGenerator<BlackNumber>(BlackNumber.class);
		return dbcpmg.generate(dbcp, sql);
	}

	@Override
	public List<BlackNumber> getBlackNumbers() {
		String sql = "select * from blacknumber ";
		ModelGenerator<BlackNumber> dbcpmg = new ModelGenerator<BlackNumber>(BlackNumber.class);
		return dbcpmg.generateList(dbcp, sql);
	}

	@Override
	public boolean saveBlackNumber(BlackNumber blackNumber, String type) {
		String sql = "";
		if (type.equalsIgnoreCase("insert"))
		{
			blackNumber.setId(getTableId("blacknumber"));
			sql = 
				"insert into blacknumber(id,number,spid,createtime) " +
				"values (" + String.valueOf(blackNumber.getId()) + ",'" + encodeDb(blackNumber.getNumber()) +
				"','" + blackNumber.getSpid() + "',now())";
			
		}
		else if (type.equalsIgnoreCase("update"))
		{
			sql = 
				"update blacknumber set number='" + encodeDb(blackNumber.getNumber()) + "'," +
						"spid='" + blackNumber.getSpid() + "' " +
				" where id=" + String.valueOf(blackNumber.getId()) + "";
		}
		else if (type.equalsIgnoreCase("delete"))
		{
			sql = "delete from blacknumber where id=" + String.valueOf(blackNumber.getId()) + "";
		}
		else
		{
			sql = "";
		}
		logger.debug("sql: " + sql);
		if (sql.length() > 0)
		{
			if (ConnectionManager.getInstance().execute(dbcp, sql))
			{
				return true;
			}
		}		
		return false;
	}

}
